'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var htmlmin = require('gulp-htmlmin');
var through2 = require('through2');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
var clean = require('gulp-clean');
var gulpSsequence = require('gulp-sequence');

String.prototype.replaceAll = function(s, d) {
    return this.replace(new RegExp(s, "gm"), d);
};

function modify(modifier) {
    return through2.obj(function(file, encoding, done) {
        var content = modifier(file);
        file.contents = new Buffer(content);
        this.push(file);
        done();
    });
}

function trimWhite(file) {
    var str = String(file.contents);
    str = str.replaceAll('}} {{', '}}{{');
    str = str.replaceAll('}}} {{{', '}}}{{{');
    return str;
}

gulp.task('default', function() {
    gulpSsequence('clean', ['sass', 'minifyHbs', 'browser-sync'], function() {
        gulp.watch('public/scss/*.scss', ['sass']);
        gulp.watch('public/views/**/*.handlebars', ['minifyHbs']);
    });
});

gulp.task('clean', function() {
    return gulp.src(['assets', 'views'], {
            read: false
        })
        .pipe(clean());
});

gulp.task('sass', function() {
    return gulp.src('public/scss/*.scss')
        .pipe(sass({
            outputStyle: 'compressed'
        }, {
            errLogToConsole: true
        }))
        .pipe(prefix('last 2 versions', '> 1%', 'ie 8', 'Android 2', 'Firefox ESR'))
        .pipe(gulp.dest('assets/css'))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('minifyHbs', function() {
    return gulp.src('public/views/**/*.handlebars')
        .pipe(htmlmin({
            collapseWhitespace: true,
            processScripts: "text/x-handlebars-template",
            minifyJS: true,
            minifyCSS: true
        }))
        .pipe(modify(trimWhite))
        .pipe(gulp.dest('views'))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('browser-sync', ['nodemon'], function() {
    browserSync.init(null, {
        proxy: 'http://localhost:3000',
        port: 7000
    });
});

gulp.task('nodemon', function(cb) {
    var started = false;
    return nodemon({
        script: 'server.js'
    }).on('start', function() {
        if (!started) {
            cb();
            started = true;
        }
    });
});